/*{
    name: 'sourceContent',
    slider: 'none',
    content: {
        use: 'sourceContent',
        rollAble: true,
        pageAble: true
    },
    data: {}


    {
        name: 'summer',
        slider: 'list',
        content: 'sourceContent',
        rollAble: true,
        pageAble: true
    }

}*/

import inquirer from "inquirer";
import fs from "fs";

function createVueFile(mes) {
  if (Array.isArray(mes)) {
    mes.forEach((single) => {
      templateReplace(single);
    });
  } else {
    templateReplace(mes);
  }
  // 模版替换模块
  function templateReplace(object) {
    //读取模版
    let _template = fs.readFileSync("./template.vue").toString();
    let _content = "{{content}}{{page}}";
    // 替换侧边栏
    _template = _template.replace(
      "<!-- slideReplace -->",
      object.slider !== "none" ? `<${object.slider}/>` : ""
    );
    // 替换内容
    if (object.content.rollAble) {
      _content = `<scrollbar>${_content}</scrollbar>`;
    }
    _content = _content.replace(
      "{{page}}",
      object.content.pageAble ? "<page :pageSize='pageSize'/>" : ""
    );
    _content = _content.replace("{{content}}", `<${object.content.use}/>`);
    _template = _template.replace("<!-- contentReplace -->", _content);
    // 替换dataObj
    if (object.content.pageAble) {
      object.data = {
        pageSize: 10,
        pageNo: 1,
      };
    }
    _template = _template.replace("dataObj", JSON.stringify(object.data));
    fs.writeFile(`./${object.name}.vue`, _template, () => {
        console.log("写入成功");
    });
    
  }
}

// 交互模块
inquirer
  .prompt([
    {
      type: "list",
      message: "选择生成方式",
      name: "renderType",
      choices: ["加载render.config.js生成", "手动选择"],
    },
  ])
  .then((answer) => {
    // 生成组件数据模块
    if (answer.renderType === "加载render.config.js生成") {
      import("./render.config.js").then((res) => {
        // 模版替换模块
        createVueFile(res.default);
      });
    } else {
      inquirer
        .prompt([
          {
            type: "input",
            message: "文件名",
            name: "name",
          },
          {
            type: "list",
            message: "选择sliderBar",
            name: "slider",
            choices: ["none", "list", "treeList"],
          },
          {
            type: "list",
            message: "选择content",
            name: "content",
            choices: ["sourceContent", "tableContent"],
          },
          {
            type: "confirm",
            name: "rollAble",
            message: "是否需要滚动",
          },
          {
            type: "confirm",
            name: "pageAble",
            message: "是否需要页码",
          },
        ])
        .then((answer) => {
          createVueFile({
            name: answer.name,
            slider: answer.slider,
            content: {
              use: answer.content,
              rollAble: answer.rollAble,
              pageAble: answer.pageAble,
            },
          });
        });
    }
  });
